package com.ruike.alisurface.ui.settings;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.VideoView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.FileUtils;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.printer.OrderTicketBean;
import com.ruike.alisurface.printer.PrinterOperateUtils;
import com.ruike.alisurface.serialport.Ttys3Utils;
import com.voodoo.lib_logcat.L;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;

public class OtherSetting_Aty extends BaseAty {
    @BindView(R.id.goback_imgv)
    ImageView gobackImgv;
    @BindView(R.id.bt_printreceipt)
    Button btPrintreceipt;
    @BindView(R.id.base_video_recording)
    Button baseVideoRecording;

    @BindView(R.id.base_video_start)
    Button baseVideoStart;
    @BindView(R.id.surface_view)
    SurfaceView mSurfaceView;
    @BindView(R.id.timer)
    Chronometer mTimer;
    @BindView(R.id.video_txcvv)
    VideoView videoPlayerTxcvv;
    @BindView(R.id.bt_start_humidifier)
    Button btStartHumidifier;
    @BindView(R.id.video_lv)
    LinearLayout video_lv;

    private SurfaceHolder mSurfaceHolder;
    private boolean isRecording = false;//标记是否已经在录制
    private MediaRecorder mRecorder;//音视频录制类
    private Camera mCamera = null;//相机
    private Camera.Size mSize = null;//相机的尺寸
    private int mCameraFacing = Camera.CameraInfo.CAMERA_FACING_FRONT;// 前置摄像头


    @Override
    protected int getLayoutResId() {
        return R.layout.app_other_setting;
    }

    @Override
    protected void initViews() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
            }
        }
        PrinterOperateUtils.getInstance().connectUsbPrinter(this);
        initTitleBar(false);

        btStartHumidifier.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showToast("点击了");

                if (btStartHumidifier.getText().equals("开启加湿器")) {
                    btStartHumidifier.setText("关闭加湿器");
                    Ttys3Utils.getInstance().isHumidifier(true);
                } else {
                    btStartHumidifier.setText("开启加湿器");
                    Ttys3Utils.getInstance().isHumidifier(false);
                }

            }
        });

        gobackImgv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        baseVideoRecording.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (baseVideoRecording.getText().equals("开始录视频")) {
                    baseVideoRecording.setText("停止录视频");
                    startRecord();
                } else {
                    baseVideoRecording.setText("开始录视频");
                    stopRecord();
                }
            }
        });

        baseVideoStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (baseVideoStart.getText().equals("播放视频")) {
                    baseVideoStart.setText("停止播放");
                    playVideo();
                } else {
                    baseVideoStart.setText("播放视频");
                    videoPlayerTxcvv.stopPlayback();
                }
            }
        });
    }

    @Override
    protected void initData() {
        try {
            initCamera();
        } catch (Exception e) {
            L.i("initCamera Exception====" + e.toString());
            video_lv.setVisibility(View.INVISIBLE);
            showErrorLongToast(e.getMessage(), 5000);
        }
        btPrintreceipt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!PrinterOperateUtils.getInstance().isConnected()) {
                    L.i("没有连接成功");
                    return;
                }
                OrderTicketBean.DataBean orderTicketBean = new OrderTicketBean.DataBean();
                orderTicketBean.setDeviceName("天津睿科");
                orderTicketBean.setPhoneNumber("13800000831");
                orderTicketBean.setPayTime("2021年07月26日");
                orderTicketBean.setOrderId("2021072310462720572625");

                List<OrderTicketBean.DataBean.ProductBeansBean> productBeans = new ArrayList<>();
                OrderTicketBean.DataBean.ProductBeansBean productBean1 = new OrderTicketBean.DataBean.ProductBeansBean();
                productBean1.setProductName("感冒灵（999）");
                productBean1.setSpecification("15/盒");
                productBean1.setUnitPrice(15);
                productBean1.setNumber(1);
                productBean1.setSubtotal(15.00);
                productBeans.add(productBean1);
                OrderTicketBean.DataBean.ProductBeansBean productBean2 = new OrderTicketBean.DataBean.ProductBeansBean();
                productBean2.setProductName("感冒清热颗粒");
                productBean2.setSpecification("5.70/盒");
                productBean2.setUnitPrice(5.70);
                productBean2.setNumber(1);
                productBean2.setSubtotal(7.50);
                productBeans.add(productBean2);

                orderTicketBean.setProductBeans(productBeans);
                orderTicketBean.setTotalPay(22.50);
                orderTicketBean.setCash(22.50);
                orderTicketBean.setMedicalInsurance(0);
                orderTicketBean.setActualTotalPay(20.50);
                orderTicketBean.setIsPrintExhort(true);
                List<OrderTicketBean.DataBean.ExhortBeansBean> exhortBeans = new ArrayList<>();
                OrderTicketBean.DataBean.ExhortBeansBean exhortBean1 = new OrderTicketBean.DataBean.ExhortBeansBean();
                exhortBean1.setProductName("感冒灵（999）");
                exhortBean1.setDescribe("开水冲服。一次10克(1袋)，一日3次。严重肝肾功能不全者禁用。");
                exhortBeans.add(exhortBean1);
                OrderTicketBean.DataBean.ExhortBeansBean exhortBean2 = new OrderTicketBean.DataBean.ExhortBeansBean();
                exhortBean2.setProductName("感冒清热颗粒");
                exhortBean2.setDescribe("开水冲服。一次1袋，一日2次，对本品过敏者禁用。严重肝肾功能不全者禁用。");
                exhortBeans.add(exhortBean2);
                orderTicketBean.setExhortBeans(exhortBeans);
                orderTicketBean.setIsPrintQrCode(true);
                orderTicketBean.setQrcode("{\"order_id\":\"2021080511310400028834\"}");
                orderTicketBean.setQrcodeDescribe("扫描二维码申请开票");
                // 打印属于耗时操作，在异步线程完成
                new Thread() {
                    @Override
                    public void run() {
                        PrinterOperateUtils.getInstance().printOrder(getResources(), orderTicketBean);
                    }
                }.start();
            }
        });


    }

    private Camera openFrontFacingCameraGingerbread() {
        int cameraCount = 0;
        Camera cam = null;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraCount = Camera.getNumberOfCameras();
        for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
            Camera.getCameraInfo(camIdx, cameraInfo);
            L.e("检查相机=cameraInfo=", cameraInfo.facing + "===");
            /* if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                try {
                    cam = Camera.open(camIdx);
                } catch (RuntimeException e) {
                    Log.e("检查相机==", "Camera failed to open: " + e.getLocalizedMessage());
                }
            } */ if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                try {
                    L.e("检查相机=cameraInfo=", cameraInfo.facing + "===");
//                    cam = Camera.open(camIdx);
                } catch (RuntimeException e) {
                    L.e("检查相机==", "Camera failed to open: " + e.getLocalizedMessage());
                }
            }
        }

        return cam;
    }

    /**
     * 初始化相机
     */
    private void initCamera() {
      /*  if (Camera.getNumberOfCameras() == 2) {
            mCamera = Camera.open(mCameraFacing);
        } else {
            mCamera = Camera.open();
        }*/
        openFrontFacingCameraGingerbread();
        mCamera = Camera.open( );

        CameraSizeComparator sizeComparator = new CameraSizeComparator();
        Camera.Parameters parameters = mCamera.getParameters();

        if (mSize == null) {
            List<Camera.Size> vSizeList = parameters.getSupportedPreviewSizes();
            Collections.sort(vSizeList, sizeComparator);

            for (int num = 0; num < vSizeList.size(); num++) {
                Camera.Size size = vSizeList.get(num);

                if (size.width >= 800 && size.height >= 480) {
                    this.mSize = size;
                    break;
                }
            }
            mSize = vSizeList.get(0);

            List<String> focusModesList = parameters.getSupportedFocusModes();

            //增加对聚焦模式的判断
            if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
            } else if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            }
            mCamera.setParameters(parameters);
        }
//        int rotation = getWindowManager().getDefaultDisplay().getRotation();
//        mCamera.setDisplayOrientation(Surface.ROTATION_180);

        mSurfaceView.setZOrderOnTop(true);
        mSurfaceView.setZOrderMediaOverlay(true);
        final SurfaceHolder holder2 = mSurfaceView.getHolder();// 取得holder
        holder2.setFormat(PixelFormat.TRANSPARENT);
        holder2.setFixedSize(1280, 720);
        holder2.setKeepScreenOn(true);

        holder2.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
                video_lv.setVisibility(View.VISIBLE);
                // 将holder，这个holder为开始在onCreate里面取得的holder，将它赋给mSurfaceHolder
                mSurfaceHolder = holder2;
                if (mCamera == null) {
                    return;
                }
                try {
                    //设置显示
                    mCamera.setPreviewDisplay(holder2);
                    mCamera.setDisplayOrientation(180);
                    mCamera.startPreview();
                } catch (Exception e) {
                    e.printStackTrace();
                    releaseCamera();
                    finish();
                }

            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                mSurfaceHolder = holder2;
            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
                // surfaceDestroyed的时候同时对象设置为null
                if (isRecording && mCamera != null) {
                    mCamera.lock();
                }
                mSurfaceView = null;
                mSurfaceHolder = null;
                releaseMediaRecorder();
                releaseCamera();
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();

        Constant.isShopShipment = true;
    }

    @Override
    public void onPause() {
        releaseCamera();
        super.onPause();
        Constant.isShopShipment = false;

    }

    /**
     * 停止录制
     */
    private void stopRecord() {
        try {
            //停止录制
            mRecorder.stop();
            mTimer.stop();
            //重置
            mRecorder.reset();
            mCamera.stopPreview();
            ;  //            mStartStop.setImageResource(R.drawable.icon_video_play);
        } catch (Exception e) {
            e.printStackTrace();
        }
        isRecording = false;
    }

    /**
     * 释放MediaRecorder
     */
    private void releaseMediaRecorder() {
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }
    }

    /**
     * 释放相机资源
     */
    private void releaseCamera() {
        try {
            if (mCamera != null) {
                mCamera.stopPreview();
                mCamera.setPreviewCallback(null);
                mCamera.unlock();
                mCamera.release();
            }
        } catch (RuntimeException e) {
        } finally {
            mCamera = null;
        }
    }

    String vedio_path;

    /**
     * 开始录制
     */
    private void startRecord() {


        mTimer.setBase(SystemClock.elapsedRealtime());
        mTimer.setFormat("计时开始 %s");
        mTimer.start();

        if (mRecorder == null) {
            mRecorder = new MediaRecorder(); // 创建MediaRecorder
        }
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.unlock();
            mRecorder.setCamera(mCamera);
        }
        try {
            // 设置音频采集方式
            mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            //设置视频的采集方式
            mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            //设置文件的输出格式
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//aac_adif， aac_adts， output_format_rtp_avp， output_format_mpeg2ts ，webm
            //设置audio的编码格式
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            //设置video的编码格式
            mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            //设置录制的视频编码比特率
            //mRecorder.setVideoEncodingBitRate(1024 * 1024);
            mRecorder.setVideoSize(1280, 720);
            //设置录制的视频帧率,注意文档的说明:
            mRecorder.setVideoFrameRate(20);

            //设置要捕获的视频的宽度和高度
            // mSurfaceHolder.setFixedSize(320, 240);//最高只能设置640x480
            //mRecorder.setVideoSize(320, 240);//最高只能设置640x480
            //设置记录会话的最大持续时间（毫秒）
            //mRecorder.setMaxDuration(60 * 1000);
            mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
            mRecorder.setOrientationHint(180);
            String path = getExternalCacheDir().getAbsolutePath();
            File dir = new File(path + "/videos");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            vedio_path = dir + "/" + "SmartDoor_video" + System.currentTimeMillis() + ".mp4";

//                mSp.put("video_path",path);
            //设置输出文件的路径
            mRecorder.setOutputFile(vedio_path);
            //准备录制
            mRecorder.prepare();
            //开始录制
            mRecorder.start();
            isRecording = true;
            //btnStartStop.setText("停止");
//                mStartStop.setImageResource(R.drawable.icon_video_stop);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private class CameraSizeComparator implements Comparator<Camera.Size> {
        public int compare(Camera.Size lhs, Camera.Size rhs) {
            if (lhs.width == rhs.width) {
                return 0;
            } else if (lhs.width > rhs.width) {
                return 1;
            } else {
                return -1;
            }
        }
    }


    public void playVideo() {
        // 显示视频播放控件
        videoPlayerTxcvv.setVisibility(View.VISIBLE);
        videoPlayerTxcvv.setVideoPath(vedio_path);
        videoPlayerTxcvv.start();
        videoPlayerTxcvv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                videoPlayerTxcvv.setVideoPath(vedio_path);
                videoPlayerTxcvv.start();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PrinterOperateUtils.getInstance().unConnectUsbPrinter();
        mTimer.stop();
        releaseCamera();
        String path = getExternalCacheDir().getAbsolutePath();
        File dir = new File(path + "/videos");
        if (dir.exists()) {
            FileUtils.deleteAllInDir(dir.getAbsolutePath());
        }
    }
}
